const express = require('express');
const router = express.Router();
const { Users, Articles } = require('../../models');
const { Op } = require('sequelize');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');


/**
 * 查询用户列表
 * GET /admin/articles
 */
router.get('/', async function (req, res) {
    try {
        const query = req.query;
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        };

        if (query.username) {
            condition.where = {
                username: {
                    [Op.like]: `%${query.username}%`
                },
            };
        }
        if (query.nikename) {
            condition.where = {
                nikename: {
                    [Op.like]: `%${query.nikename}%`
                },
            };
        }
        if (query.email) {
            condition.where = {
                email: {
                    [Op.like]: `%${query.email}%`
                },
            };
        }

        const { count, rows } = await Users.findAndCountAll(condition);
        success(res, '查询用户信息列表成功。', {
            articles: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize,
            }
        });
    } catch (error) {
        failure(res, error);
    }
});

router.get('/user/:id', async function (req, res) {
    try {

        
        const {id} = req.params; // 假设用户信息存储在 req.user.id 中

        const condition = {
            order: [['id', 'DESC']],
            attributes: [
                'id', 'classId', 'title', 'content', 'image_url',
                'status', 'likesCount', 'collect', 'sort_id',
                'createdAt',
            ],
        };

        if (id) {
            condition.where = {
                publisher_id: {
                    [Op.eq]: `${id}`
                },
            };
        }

        const { count, rows } = await Articles.findAndCountAll(condition);

        success(res, '查询文章列表成功。', {
            rows,
            pagination: {
                total: count,
            }
        });
    } catch (error) {
        failure(res, error);
    }
});
/**
 * 查询用户详情
 * GET /admin/articles/:id
 */
router.get('/:id', async function (req, res) {
    try {
        const users = await getUsers(req);
        success(res, '查询用户成功。', { users });
    } catch (error) {
        failure(res, error);
    }
});

/**
 * 创建用户
 * POST /admin/articles
 */
router.post('/', async function (req, res) {
    try {
        // jwt.sign(Payload, secretkey, option)

        const body = filterBody(req);
        const existingUser = await Users.findOne({
            where: {
                username: body.username
            }
        });
        if (existingUser) {
            // 如果存在相同的 username，则返回错误提示
            return res.status(400).json({
                status: false,
                message: '用户名重复',
                // errors: [error.message]
            });;
        }
        const users = await Users.create(body);
        success(res, '新建用户成功。', { users }, 201);
    } catch (error) {
        failure(res, error);
    }
});

/**
 * 更新用户
 * PUT /admin/articles/:id
 */
router.put('/:id', async function (req, res) {
    try {
        const users = await getUsers(req);
        const body = filterBody(req);
        await users.update(body);
        success(res, '更新用户信息成功。', { users });
    } catch (error) {
        failure(res, error);
    }
});
router.delete('/:id', async function (req, res) {
    try {
        const users = await getUsers(req);

        await users.destroy();
        success(res, '删除用户成功。');
    } catch (error) {
        failure(res, error);
    }
});

/**
 * 公共方法：查询当前用户
 */
async function getUsers(req) {
    const { id } = req.params;

    const users = await Users.findByPk(id);
    if (!users) {
        throw new NotFoundError(`ID: ${id}的用户未找到。`)
    }

    return users;
}

/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
    return {
        username: req.body.username,
        password: req.body.password,
        email: req.body.email,
        permissions: req.body.permissions,
        user_url: req.body.user_url,
    };
}

module.exports = router;
